/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ufrn.dimap.projetodetalhadodesoftware.chatrmi.view.gui;

import br.ufrn.dimap.projetodetalhadodesoftware.chatrmi.model.actor.ClientModel;
import br.ufrn.dimap.projetodetalhadodesoftware.chatrmi.view.ClientView;
import br.ufrn.dimap.projetodetalhadodesoftware.chatrmi.controller.parental.EnglishParentalController;
import br.ufrn.dimap.projetodetalhadodesoftware.chatrmi.controller.parental.FrenchParentalController;
import br.ufrn.dimap.projetodetalhadodesoftware.chatrmi.controller.parental.ParentalController;
import br.ufrn.dimap.projetodetalhadodesoftware.chatrmi.controller.parental.PortugueseParentalController;
import br.ufrn.dimap.projetodetalhadodesoftware.chatrmi.controller.ClientControler;
import br.ufrn.dimap.projetodetalhadodesoftware.chatrmi.controller.ChatInterface;
import br.ufrn.dimap.projetodetalhadodesoftware.chatrmi.controller.ClientControllerInterface;
import java.net.MalformedURLException;
import java.rmi.RemoteException;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author logan
 */
public class ClientGUIWindow extends javax.swing.JFrame implements ClientView {

    /**
     * Creates new form ClientWindow
     */
    ClientControllerInterface clientControllerInterface;
    ParentalController parentalController;
    boolean registered = false;
	
    public ClientGUIWindow() {
        initComponents();
		//English is default
        parentalController = new EnglishParentalController();
        parentalController.on();
         try {
            connect();
            this.setVisible(true);
        } catch (RemoteException ex) {
           JOptionPane.showMessageDialog(this, "Erro ao se conectar!\n Tente novamente agora ou mais tarde.", "Erro", JOptionPane.ERROR_MESSAGE);
        } catch (MalformedURLException ex) {
            JOptionPane.showMessageDialog(this, "Erro ao se conectar!\n Tente novamente agora ou mais tarde.", "Erro", JOptionPane.ERROR_MESSAGE);
        }catch(Exception e){
            JOptionPane.showMessageDialog(this, "Erro ao se conectar!\n Tente novamente agora ou mais tarde.", "Erro", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void connect() throws RemoteException, MalformedURLException {
        ClientModel clientModel = new ClientModel(jTextFieldName.getText());
        clientControllerInterface = new ClientControler(clientModel, this, "localhost", getNumPort());

        clientControllerInterface.getReferenceServer();

        displayChatRooms(clientControllerInterface.getListChats().iterator());

        
    }

    private int getNumPort(){
        Random random = new Random();

        return 1025 + random.nextInt(60000);
    }

    private void connectChat() throws RemoteException, MalformedURLException {

        if (!registered) {
            clientControllerInterface.createRegister(jTextFieldName.getText());
            registered = true;
        }else{
            clientControllerInterface.disconnectChat();
        }
        ChatInterface chat = getChat(jComboBoxChatList.getSelectedItem().toString());
        clientControllerInterface.getReferenceChat(chat);
        clientControllerInterface.connectChat();
        displayMessage("\nConectado com sucesso!\n");
        currentChat.setText("CONNECTED TO: "+chat.getTheme());
    }

    private ChatInterface getChat(String theme) throws RemoteException {
        System.out.println(theme);
        List<ChatInterface> lista = clientControllerInterface.getListChats();
        Iterator<ChatInterface> chats = lista.iterator();
        while (chats.hasNext()) {
            ChatInterface chat = chats.next();
            if (chat.getTheme().equals(theme)) {
                return chat;
            }
        }

        return null;
    }

private void sendMessage() throws RemoteException {
        String message = jTextFieldMesg.getText();
        String user = jTextFieldName.getText();
        message = "\n"+user+" diz:\n"+message;
        clientControllerInterface.sendMessage(message);

        jTextFieldMesg.setText("");
    }
	
	
	    //Strategy Pattern
    public void setEnglishParentalController(){
        parentalController = new EnglishParentalController();
        parentalController.on();
        System.gc();
    }
    public void setPortugueseParentalController(){
        parentalController = new PortugueseParentalController();
        parentalController.on();
        System.gc();
    }
    public void setFrenchParentalController(){
        parentalController = new FrenchParentalController();
        parentalController.on();
        System.gc();
    }
    public void setOffParentalController(){
        parentalController.off();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jFrame1 = new javax.swing.JFrame();
        buttonGroupParentalController = new javax.swing.ButtonGroup();
        jLabel2 = new javax.swing.JLabel();
        jTextFieldName = new javax.swing.JTextField();
        jComboBoxChatList = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextAreaChat = new javax.swing.JTextArea();
        jTextFieldMesg = new javax.swing.JTextField();
        jButtonConnect = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        jTnumberUsers = new javax.swing.JTextField();
        jLabelParentalController = new javax.swing.JLabel();
        jRadioButtonPortuguese = new javax.swing.JRadioButton();
        jRadioButtonEnglish = new javax.swing.JRadioButton();
        jRadioButtonOff = new javax.swing.JRadioButton();
        jRadioButtonFrench = new javax.swing.JRadioButton();
        currentChat = new javax.swing.JLabel();

        jLabel1.setText("jLabel1");

        javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane());
        jFrame1.getContentPane().setLayout(jFrame1Layout);
        jFrame1Layout.setHorizontalGroup(
            jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        jFrame1Layout.setVerticalGroup(
            jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("CLIENT");
        setResizable(false);

        jLabel2.setText("Nickname:");

        jComboBoxChatList.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBoxChatListActionPerformed(evt);
            }
        });

        jLabel3.setText("Lista de Chats:");

        jTextAreaChat.setBackground(new java.awt.Color(204, 204, 204));
        jTextAreaChat.setColumns(20);
        jTextAreaChat.setEditable(false);
        jTextAreaChat.setRows(5);
        jScrollPane1.setViewportView(jTextAreaChat);

        jTextFieldMesg.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldMesgActionPerformed(evt);
            }
        });

        jButtonConnect.setText("Connect");
        jButtonConnect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonConnectActionPerformed(evt);
            }
        });

        jLabel5.setText("Number Users:");

        jLabelParentalController.setText("Parental Control");

        buttonGroupParentalController.add(jRadioButtonPortuguese);
        jRadioButtonPortuguese.setText("Portuguese");
        jRadioButtonPortuguese.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButtonPortugueseActionPerformed(evt);
            }
        });

        buttonGroupParentalController.add(jRadioButtonEnglish);
        jRadioButtonEnglish.setText("English");
        jRadioButtonEnglish.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButtonEnglishActionPerformed(evt);
            }
        });

        buttonGroupParentalController.add(jRadioButtonOff);
        jRadioButtonOff.setText("Off");
        jRadioButtonOff.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButtonOffActionPerformed(evt);
            }
        });

        buttonGroupParentalController.add(jRadioButtonFrench);
        jRadioButtonFrench.setText("French");
        jRadioButtonFrench.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButtonFrenchActionPerformed(evt);
            }
        });

        currentChat.setBackground(new java.awt.Color(0, 0, 153));
        currentChat.setText("                                                                          ");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jTextFieldMesg, javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jTextFieldName, javax.swing.GroupLayout.PREFERRED_SIZE, 307, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(40, 40, 40)
                                .addComponent(jButtonConnect))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(jRadioButtonPortuguese)
                                .addGap(18, 18, 18)
                                .addComponent(jRadioButtonEnglish)
                                .addGap(18, 18, 18)
                                .addComponent(jRadioButtonFrench)
                                .addGap(18, 18, 18)
                                .addComponent(jRadioButtonOff))
                            .addComponent(jLabelParentalController, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(41, 41, 41)
                                .addComponent(jComboBoxChatList, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 563, Short.MAX_VALUE))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(currentChat)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 167, Short.MAX_VALUE)
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTnumberUsers, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(40, 40, 40))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(currentChat)
                    .addComponent(jLabel5)
                    .addComponent(jTnumberUsers, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(22, 22, 22)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextFieldName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonConnect))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jComboBoxChatList, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 193, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jTextFieldMesg, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jLabelParentalController)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jRadioButtonPortuguese)
                    .addComponent(jRadioButtonEnglish)
                    .addComponent(jRadioButtonFrench)
                    .addComponent(jRadioButtonOff))
                .addContainerGap(26, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonConnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonConnectActionPerformed
        try {
            connectChat();
        } catch (MalformedURLException ex) {
            JOptionPane.showMessageDialog(this, "Erro ao se conectar!\n Tente novamente agora ou mais tarde.", "Erro", JOptionPane.ERROR_MESSAGE);
        } catch (RemoteException ex) {
            JOptionPane.showMessageDialog(this, "Erro ao se conectar!\n Tente novamente agora ou mais tarde.", "Erro", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jButtonConnectActionPerformed

    private void jTextFieldMesgActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldMesgActionPerformed
        try {
            if(!jTextFieldMesg.getText().isEmpty()){                               
            sendMessage();
            }
        } catch (RemoteException ex) {
            Logger.getLogger(ClientGUIWindow.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jTextFieldMesgActionPerformed

    private void jRadioButtonPortugueseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonPortugueseActionPerformed
        setPortugueseParentalController();
    }//GEN-LAST:event_jRadioButtonPortugueseActionPerformed

    private void jRadioButtonEnglishActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonEnglishActionPerformed
        setEnglishParentalController();
    }//GEN-LAST:event_jRadioButtonEnglishActionPerformed

    private void jRadioButtonOffActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonOffActionPerformed
        setOffParentalController();
    }//GEN-LAST:event_jRadioButtonOffActionPerformed

    private void jRadioButtonFrenchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonFrenchActionPerformed
        setFrenchParentalController();
    }//GEN-LAST:event_jRadioButtonFrenchActionPerformed

    private void jComboBoxChatListActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxChatListActionPerformed
        if (jComboBoxChatList.getSelectedIndex() != -1) {
            try {
                updateQuantityUsersChat(clientControllerInterface.getListChats().get(jComboBoxChatList.getSelectedIndex()).getNumberClients());
            } catch (RemoteException ex) {
                JOptionPane.showMessageDialog(this, "Erro ao atualizar quantidade de usuarios");
            }
        }
    }//GEN-LAST:event_jComboBoxChatListActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ClientGUIWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ClientGUIWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ClientGUIWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ClientGUIWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new ClientGUIWindow();
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroupParentalController;
    private javax.swing.JLabel currentChat;
    private javax.swing.JButton jButtonConnect;
    private javax.swing.JComboBox jComboBoxChatList;
    private javax.swing.JFrame jFrame1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabelParentalController;
    private javax.swing.JRadioButton jRadioButtonEnglish;
    private javax.swing.JRadioButton jRadioButtonFrench;
    private javax.swing.JRadioButton jRadioButtonOff;
    private javax.swing.JRadioButton jRadioButtonPortuguese;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextAreaChat;
    private javax.swing.JTextField jTextFieldMesg;
    private javax.swing.JTextField jTextFieldName;
    private javax.swing.JTextField jTnumberUsers;
    // End of variables declaration//GEN-END:variables

    public void displayMessage(String message) {
        jTextAreaChat.append(parentalController.filter(message));
    }

    public void updateQuantityUsersChat(Integer quantity) {
        jTnumberUsers.setText(quantity.toString());
    }

    public void displayChatRooms(Iterator<ChatInterface> chats) {
        jComboBoxChatList.removeAllItems();
        ChatInterface chat = null;
        while (chats.hasNext()) {
            chat = chats.next();
            try {
                jComboBoxChatList.addItem(chat.getTheme());
            } catch (RemoteException ex) {
                Logger.getLogger(ClientGUIWindow.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    }
}
